# -*- coding: utf-8 -*-
# @Time        :2025/3/2 11:05
# @Author      :文刀水寿
# @File        : 11_爬虫_urllib_ajax的post请求肯德基官网.py
"""
 @Description :
"""
# 1页
# https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname
# 请求方法:
# POST
# cname: 北京
# pid:
# pageIndex: 1
# pageSize: 10

# 2页
# https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname
# cname: 北京
# pid:
# pageIndex: 2
# pageSize: 10

import urllib.request
import urllib.parse


def create_request(page):
    base_url = 'https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'

    headers = {
        'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Mobile Safari/537.36 Edg/133.0.0.0',
        'x-requested-with': 'XMLHttpReques'
    }

    data = {
        'cname': '北京',
        'pid': '',
        'pageIndex': page,
        'pageSize': '10'
    }

    # post请求的参数，必须要编码
    data = urllib.parse.urlencode(data).encode('utf8')

    # post请求的参数，是不会拼接在url后边的，而是放在请求对象定制的参数中
    # post请求的参数，必须编码
    request = urllib.request.Request(url=base_url, data=data, headers=headers)
    return request


def get_content(request):
    # 模拟向服务器发送请求
    response = urllib.request.urlopen(request)

    content = response.read().decode('utf8')
    return content


def down_load(content, page):
    with open('cantingweizhi' + str(page) + '.json', 'w', encoding='utf8') as fp:
        fp.write(content)


if __name__ == '__main__':
    start_page = int(input('请输入起始页'))
    end_page = int(input('请输入终止页'))

    for page in range(start_page, end_page + 1):
        request = create_request(page)

        content = get_content(request)

        down_load(content, page)
